<template>
  <div class="login-container">
    <div class="login-form">
      <h3>用户登录</h3>

      <!-- 用户名输入区 -->
      <div class="form-group">
        <label>用户名</label>
        <input
            v-model="form.username"
            type="text"
            placeholder="请输入用户名"
            :class="{'error-input': errors.username}"
        />
        <p v-if="errors.username" class="error-message">{{ errors.username }}</p>
      </div>

      <!-- 密码输入区 -->
      <div class="form-group">
        <label>密码</label>
        <input
            v-model="form.password"
            type="password"
            placeholder="请输入密码（至少6位）"
            :class="{'error-input': errors.password}"
        />
        <p v-if="errors.password" class="error-message">{{ errors.password }}</p>
      </div>

      <!-- 角色选择区 -->
      <div class="form-group">
        <label>角色</label>
        <select v-model="form.role" :class="{'error-input': errors.role}">
          <option value="">请选择角色</option>
          <option value="customer">顾客</option>
          <option value="employee">员工</option>
          <option value="admin">管理员</option>
        </select>
        <p v-if="errors.role" class="error-message">{{ errors.role }}</p>
      </div>

      <!-- 验证码输入区 -->
      <div class="form-group">
        <label>验证码</label>
        <div class="verify-code-row">
          <input
              v-model="form.verifyCode"
              type="text"
              placeholder="请输入验证码"
              :class="{'error-input': errors.verifyCode}"
          />
          <img
              :src="verifyCodeUrl"
              @click="refreshVerifyCode"
              alt="验证码图片"
              class="verify-code-image"
              :class="{'shake': errors.verifyCode}"
          />
        </div>
        <p v-if="errors.verifyCode" class="error-message">{{ errors.verifyCode }}</p>
      </div>

      <button @click="login">登录</button>
      <p v-if="errors.system" class="error-message">{{ errors.system }}</p>

      <!-- 修改：将router-link改为普通文本，并添加点击事件 -->
      <p class="register-link">
        没有账号？
        <span @click="showAdminMessage" class="register-text">立即注册</span>
      </p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import axios from 'axios'

export default {
  setup() {
    const store = useStore()
    const router = useRouter()

    // 表单数据
    const form = ref({
      username: '',
      password: '',
      role: '',
      verifyCode: ''
    })

    // 错误提示对象
    const errors = ref({
      username: '',
      password: '',
      role: '',
      verifyCode: '',
      system: ''
    })

    const verifyCodeUrl = ref('')

    // 刷新验证码
    const refreshVerifyCode = () => {
      verifyCodeUrl.value = `/code?${new Date().getTime()}`
      form.value.verifyCode = ''
      errors.value.verifyCode = ''
    }

    // 表单校验
    const validateForm = () => {
      Object.keys(errors.value).forEach(key => {
        errors.value[key] = ''
      })

      let isValid = true

      if (!form.value.username.trim()) {
        errors.value.username = '用户名不能为空'
        isValid = false
      } else if (form.value.username.length > 20) {
        errors.value.username = '用户名不能超过20个字符'
        isValid = false
      }

      if (!form.value.password) {
        errors.value.password = '密码不能为空'
        isValid = false
      } else if (form.value.password.length < 6) {
        errors.value.password = '密码长度不能少于6位'
        isValid = false
      }

      if (!form.value.role) {
        errors.value.role = '请选择登录角色'
        isValid = false
      }

      if (!form.value.verifyCode.trim()) {
        errors.value.verifyCode = '验证码不能为空'
        isValid = false
      } else if (form.value.verifyCode.length < 4) {
        errors.value.verifyCode = '验证码格式错误（请输入4位字符）'
        isValid = false
      }

      return isValid
    }

    // 统一处理错误信息
    const handleLoginError = (message) => {
      if (message.includes('验证码')) {
        errors.value.verifyCode = message
        refreshVerifyCode()
      } else if (message.includes('用户名')) {
        errors.value.username = message
      } else if (message.includes('密码')) {
        errors.value.password = message
      } else if (message.includes('角色')) {
        errors.value.role = message
      } else {
        errors.value.system = message
      }
    }

    // 登录逻辑
    const login = async () => {
      if (!validateForm()) {
        return
      }

      try {
        const loginRes = await axios.post(
            '/auth/login',
            {
              username: form.value.username,
              password: form.value.password,
              role: form.value.role,
              verifyCode: form.value.verifyCode
            },
            {
              headers: { 'Content-Type': 'application/json' }
            }
        )

        if (loginRes.status === 200 && loginRes.data.role) {
          store.commit('setUser', loginRes.data.user)
          store.commit('setRole', loginRes.data.role)
          localStorage.setItem('user', JSON.stringify(loginRes.data.user))
          localStorage.setItem('role', loginRes.data.role)

          switch (loginRes.data.role) {
            case 'customer':
              router.push('/customer/home')
              break
            case 'employee':
              router.push('/employee/dashboard')
              break
            case 'admin':
              router.push('/admin/manage')
              break
            default:
              errors.value.system = '未知角色类型，请联系管理员'
          }
        } else {
          const errorData = loginRes.data || {}
          handleLoginError(errorData.message || '登录失败')
        }
      } catch (error) {
        if (error.response) {
          const errorData = error.response.data || {}
          const errorMessage = errorData.message || `请求错误（${error.response.status}）`

          if (errorMessage.includes('验证码')) {
            handleLoginError(errorMessage)
          } else {
            switch (error.response.status) {
              case 401:
                errors.value.system = '身份验证失败，请检查账号密码'
                break
              case 403:
                errors.value.system = '没有权限登录此角色'
                break
              case 500:
                errors.value.system = '服务器异常，请稍后再试'
                break
              default:
                errors.value.system = errorMessage
            }
          }
        } else if (error.request) {
          errors.value.system = '网络连接失败，请检查网络'
        } else {
          errors.value.system = '登录过程出错，请重试'
        }
        console.error('登录错误:', error)
      }
    }

    // 新增：显示联系管理员提示
    const showAdminMessage = () => {
      alert('请联系管理员开通账号')
    }

    onMounted(() => {
      refreshVerifyCode()
    })

    return {
      form,
      verifyCodeUrl,
      errors,
      refreshVerifyCode,
      login,
      showAdminMessage // 导出新增方法
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-form {
  width: 300px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 3px;
  box-sizing: border-box;
  transition: border-color 0.3s;
}

.error-input {
  border-color: #ff4d4f !important;
}

.verify-code-row {
  display: flex;
}

.verify-code-row input {
  flex: 1;
  margin-right: 10px;
}

.verify-code-image {
  width: 100px;
  height: 34px;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 3px;
}

.shake {
  animation: shake 0.5s;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

button {
  width: 100%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

.error-message {
  color: #ff4d4f;
  margin-top: 4px;
  font-size: 13px;
  line-height: 1.4;
}

.register-link {
  margin-top: 15px;
  text-align: center;
  font-size: 14px;
}

/* 新增：注册文本样式 */
.register-text {
  color: #007BFF;
  text-decoration: none;
  cursor: pointer;
}

.register-text:hover {
  text-decoration: underline;
}
</style>